import type { MenuDataItem } from '@ant-design/pro-layout';
import { PageLoading } from '@ant-design/pro-layout';
import type { RunTimeLayoutConfig } from 'umi';
import { history } from 'umi';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import type { RequestConfig } from '@@/plugin-request/request';
import { menus } from '@/services/abis/account';
import { MenuIconEnum } from '@/services/abis/enum';
import { Link } from '@umijs/preset-dumi/lib/theme';

const loginPath = '/user/login';

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  token?: string;
  menu?: MenuDataItem[];
}> {
  const token = localStorage.getItem('token') || '';
  let menu: MenuDataItem[] = [];
  if (token && menu.length == 0) {
    const { data } = await menus();
    menu = data;
  }

  return {
    token: token,
    menu: menu,
  };
}

const menuGenerate = (menuData: MenuDataItem[]): MenuDataItem[] =>
  menuData.map(({ icon, children, ...item }) => {
    return {
      ...item,
      icon: icon && MenuIconEnum[icon as string],
      children: children && menuGenerate(children),
    };
  });

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.token && location.pathname !== loginPath) {
        history.push(loginPath);
      }
      if (initialState?.token && location.pathname === loginPath) {
        history.push('/');
      }
    },
    menuHeaderRender: undefined,
    menu: {
      locale: false
    },
    menuDataRender: () => menuGenerate(initialState?.menu || []),
    menuItemRender: (menuItemProps, defaultDom) => {
      if (menuItemProps.isUrl || !menuItemProps.path) {
        return defaultDom;
      }
      return (
        <Link to={menuItemProps.path}>
          {menuItemProps.pro_layout_parentKeys &&
            menuItemProps.pro_layout_parentKeys.length > 0 &&
            menuItemProps.icon}
          {defaultDom}
        </Link>
      );
    },
  };
};

// @ts-ignore
const authHeaderInterceptors = (url: string, options: RequestOptionsInit) => {
  /**
   * 处理请求参数中的 pageSize，将其由驼峰转为下划线 page_size
   * 由于 pageSize 是 antd 规范，只能在这里做统一处理
   */
  if (options.data && options.data.pageSize) {
    options.data.page_size = options.data.pageSize
    delete options.data.pageSize
  }
  if (options.params && options.params.pageSize) {
    options.params.page_size = options.params.pageSize
    delete options.params.pageSize
  }

  const tokenStr = localStorage.getItem('token');
  let authHeader = {};
  if (tokenStr) {
    authHeader = {
      Authorization: `Bearer ${tokenStr}`,
    };
  }
  return {
    url: url,
    options: { ...options, interceptors: true, headers: authHeader },
  };
};

// http 请求配置
export const request: RequestConfig = {
  errorConfig: {
    adaptor: (resData) => {
      let errorMsg: string;
      if (resData.data) {
        errorMsg = `${resData.message}: ${resData.data}`;
      } else {
        errorMsg = `${resData.message}`;
      }

      return {
        data: resData.data,
        success: resData.code === 1000,
        errorMessage: errorMsg,
        errorCode: resData.code,
        showType: 1,
      };
    },
  },
  // request 请求拦截器配置
  requestInterceptors: [authHeaderInterceptors],
  // response 响应拦截器
  responseInterceptors: [],
};
